﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Text;
using blackhouse.Web.FasterFiles;
using blackhouse.JavaScript.JQuery;

namespace blackhouse.Web.Controls {
    public class CountryTextBox : TextBox {

        #region Fields

        private static string js;

        #endregion

        #region Event Handlers

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            if (string.IsNullOrEmpty(js))
                js = this.BuildJSArray();
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeFileBasedOnJQuery("blackhouse.Web.Controls.CountryTextBox.js,blackhouse.Web.Controls");

            FasterFilesProvider ffp = new FasterFilesProvider();
            ffp.AddAfterScript(js);
        }

        #endregion

        #region Methods

        private string BuildJSArray() {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("var countries = new Array();");
            var regions = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(c => new RegionInfo(c.Name));
            foreach (RegionInfo region in RegionInfoExtend.GetRegionsNativeOrdered()) {
                sb.AppendFormat("countries.push({{label: '{0}', value: '{1}'}});", region.NativeName.ReplaceEx("'", @"\'"), region.ThreeLetterWindowsRegionName);
                sb.AppendLine();
            }
            return sb.ToString();
        }

        #endregion

    }
}